# -*- coding: utf-8 -*-
from app import create_app
from src.connector import get_client
from src.db_tools import check_if_user_exist, check_if_username_exist
from src.db_tools import *
from src.statistics import *

import logging
import json
import hashlib
from bson import json_util, ObjectId
from flask import jsonify, request
from flask_cors import CORS

app = create_app('development')
CORS(app, supports_credentials=True)

"""
RUN LOCALLY AS TEST MODE
"""
@app.route('/test', methods=['GET'])
def test():
    return {"Hello": "World!"}

@app.route('/test/error', methods=['GET', 'POST'])
def error():
    return {"code" : 50001, "showMsg" : True, "message" : "Test login error...", "msgType": 'error'}

# TODO: And constaint, just admin can invoke this
@app.route('/user/api/v1/get_all_users', methods=['GET'])
def get_all_users():
    app.logger.info("-----invoke all user data-----")
    data = db_get_all_users()
    return jsonify(data)

@app.route('/tags/api/v1/get_all_tags', methods=['GET'])
def get_all_tags():
    app.logger.info("----invoke get all tags-----")
    data = db_get_all_tags()
    return jsonify(data)

# DEBUG: Can't get post arguments ---DONE---
@app.route('/user/api/v1/login', methods=['POST'])
def login():
    app.logger.debug("----invoke login method-----")
    get_data = request.get_data(as_text=True)
    dict_data = json.loads(get_data)
    app.logger.debug(dict_data)
    res = db_login(dict_data)
    return res


@app.route('/user/api/v1/get_user_info', methods=['GET'])
def get_user_info():
    app.logger.debug("----invoke get user info method-----")
    try:
        token = request.headers["X-Token"]
        res = db_get_user_info(token)
        return res
    except Exception as e:
        return { "message" : "GET user token failed! ", "code" : 50002}

@app.route('/user/api/v1/logout', methods=['POST'])
def logout():
    app.logger.debug("----invoke logout method-----")
    try:
        token = request.headers["X-Token"]
        app.logger.debug("log out token: " + token)
        res = db_logout(token)
        return res
    except Exception as e:
        app.logger.error(e)
        return {"message" : "Log out failed due to X-Token.", "code": 50003}


@app.route('/user/api/v1/create_user', methods=['POST'])
def create_user():
    app.logger.info("----invoke create user----")
    get_data = request.get_data(as_text=True)
    dict_data = json.loads(get_data)
    app.logger.debug(dict_data)
    res = db_create_user(dict_data)
    return res


@app.route('/user/api/v1/update_profile', methods=['POST'])
def update_profile():
    app.logger.info("----invoke update profile----")
    get_data = request.get_data(as_text=True)
    dict_data = json.loads(get_data)
    app.logger.debug(dict_data)
    res = db_update_profile(request.headers, dict_data)
    app.logger.debug(res)
    return res


@app.route('/user/api/v1/change_password', methods=['POST'])
def change_password():
    app.logger.info("----invoke change password----")
    get_data = request.get_data(as_text=True)
    dict_data = json.loads(get_data)
    app.logger.debug(dict_data)
    res = db_change_password(request.headers, dict_data)
    app.logger.debug(res)
    return res

#==========================CLASSIFICATION API===========================
@app.route('/classification/api/v1/get_classification', methods=['GET'])
def get_classification():
    app.logger.info("----invoke get classification----")
    # get_data = request.args.get()
    # app.logger.debug(get_date)
    res = db_get_classification(request.headers)
    app.logger.debug(res)
    return res

@app.route('/classification/api/v1/update_classification', methods=['POST'])
def update_classification():
    app.logger.info("----invoke update classification----")
    get_data = request.get_data(as_text=True)
    dict_data = json.loads(get_data)
    app.logger.debug(dict_data)
    res = db_update_classification(request.headers, dict_data)
    app.logger.debug(res)
    return res


#==========================DREAMS API==============================
@app.route('/dreams/api/v1/get_dreams', methods=['GET'])
def get_dreams():
    app.logger.info("----invoke get dreams----")
    res = db_get_dreams(request.headers)
    app.logger.debug(res)
    return res

@app.route('/dreams/api/v1/get_dream_by_id', methods=['GET'])
def get_dreams_by_id():
    app.logger.info("----invoke get dream by Id----")
    get_data = request.args.get("id")
    res = db_get_dream_by_id(request.headers, get_data)
    app.logger.debug(res)
    return res

@app.route('/dreams/api/v1/update_dream_by_id', methods=['POST'])
def update_dream_by_id():
    app.logger.info("----invoke update dream by Id----")
    get_data = request.get_data(as_text=True)
    dict_data = json.loads(get_data)
    app.logger.debug(dict_data)
    res = db_update_dream_by_id(request.headers, dict_data)
    app.logger.debug(res)
    return res

@app.route('/dreams/api/v1/create_dream', methods=['POST'])
def create_dream():
    app.logger.info("----invoke update dream by Id----")
    get_data = request.get_data(as_text=True)
    dict_data = json.loads(get_data)
    app.logger.debug(dict_data)
    res = db_create_dream(request.headers, dict_data)
    app.logger.debug(res)
    return res

@app.route('/dreams/api/v1/delete_dream_by_id', methods=['POST'])
def delete_dream_by_id():
    app.logger.info("----invoke update dream by Id----")
    get_data = request.get_data(as_text=True)
    dict_data = json.loads(get_data)
    app.logger.debug(dict_data)
    res = db_delete_dream_by_id(request.headers, dict_data)
    app.logger.debug(res)
    return res

#=================Statistics API==================
@app.route('/statistics/api/v1/get_barchart_data', methods=['GET'])
def get_barchart_data():
    app.logger.info("----invoke get_barchart_data method----")
    res = gen_barchart_data(request.headers)
    app.logger.debug(res)
    return res

@app.route('/statistics/api/v1/get_piechart_data', methods=['GET'])
def get_piechart_data():
    app.logger.info("----invoke get_piechart_data method----")
    res = gen_piechart_data(request.headers)
    app.logger.debug(res)
    return res

if __name__ == "__main__":
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    ch = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s - %(funcName)s - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    app.logger.addHandler(ch)
    app.logger.debug('----Start app----')
    app.run(host='0.0.0.0', port=5000, debug=True)
    app.logger.debug('-----App Stop----')
